<?php

class DbCondition {

	/**
	 * @return NullDbCondition
	 */
	public static function createNull() { return new NullDbCondition();	}
	/**
	 * @return NullDbCondition
	 */
	public static function createSimpleEqual($field, $value) {
	    $instance = new DbCondition();
	    $instance->addEqualCond($field, $value);
	    return $instance;
	}

	private $sSql = '';
	public function getSQL() {

		$sql = $this->sSql;

		$arrOrders = array();
		foreach ($this->hOrderBy as $field => $direction) {
		    $arrOrders[] = $field . ' ' . $direction;
		}

		if ($arrOrders) {
            $sql .= ' ORDER BY ' . implode(', ', $arrOrders) . ' ';
		}

		if (($this->limitStart !== null) &&
			($this->limitNum   !== null)
		) {
			$sql .= ' LIMIT ?,? ';
		}

		return $sql;
	}

	private $arrParams = array();
	public function getParams() {

		$arrParams = $this->arrParams;

		if (($this->limitStart !== null) &&
			($this->limitNum   !== null)
		) {
			$arrParams[] = $this->limitStart;
			$arrParams[] = $this->limitNum;
		}

		return $arrParams;
	}

	private $limitStart = null;
	private $limitNum = null;

	public function setLimit($start, $num) {
		$this->limitStart = $start;
		$this->limitNum = $num;
	}

	private $hOrderBy = array();

	public function addDescOrderBy($field) {
        $this->hOrderBy[$field] = 'DESC';
	}

	public function addAscOrderBy($field) {
        $this->hOrderBy[$field] = 'ASC';
	}

	public function addGreatThenCond($field, $value) {
	    $this->addPrefixedCond($field, '>', $value);
	}

	public function addLessThenCond($field, $value) {
	    $this->addPrefixedCond($field, '<', $value);
	}

	public function addGreatThenOrEqualCond($field, $value) {
	    $this->addPrefixedCond($field, '>=', $value);
	}

	public function addLessThenOrEqualCond($field, $value) {
	    $this->addPrefixedCond($field, '<=', $value);
	}

	public function addEqualCond($field, $value) {
	    $this->addPrefixedCond($field, '=', $value);
	}

	public function addNotEqualCond($field, $value) {
	    $this->addPrefixedCond($field, '!=', $value);
	}

	public function addLikeCond($field, $value) {
	    $this->addPrefixedCond($field, 'LIKE', $value);
	}

	private function addPrefixedCond($field, $prefix, $value) {

		$this->sSql .= ($this->sSql) ?
			' AND' :
 			' WHERE';

		$this->sSql .= " $field $prefix ? ";
		$this->arrParams[] = $value;
	}
}


final class NullDbCondition extends DbCondition {

	public function getSQL() { return ''; }

	public function getParams() { return array(); }

	public function addEqualCond($field, $value) {
		throw new Exception('method not supported by '. get_class());
	}
}


?>